package com.tarena.luban.demo.gateway.filters;

import com.alibaba.fastjson.JSON;
import com.tarena.luban.demo.gateway.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.function.Supplier;

@Component
@Slf4j
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始解析token");
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //name=wang
        //name=wang&token
        List<String> token = queryParams.get("token");
        if (!CollectionUtils.isEmpty(token)&& StringUtils.isNotEmpty(token.get(0))){
            String value = token.get(0);
            //10位整数
            boolean matches = value.matches("^\\d{1,10}$");
            if (matches){
                return chain.filter(exchange);
            }
        }
        return fail(exchange);
    }

    private Mono<Void> fail(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        Result<String> result=new Result<>();
        result.setData(null);
        result.setMessage("token验证失败");
        result.setCode("200");
        //获取一个publisher对象 定义输出数据,定义输出格式
        Mono<DataBuffer> writeData = Mono.fromSupplier(new Supplier<DataBuffer>() {
            public DataBuffer get() {
                //封装result到响应数据
                String json = JSON.toJSONString(result);
                log.info("即将返回的结果:{}",json);
                DataBufferFactory dataBufferFactory = response.bufferFactory();
                //使用工厂类包裹json字符串
                return dataBufferFactory.wrap(json.getBytes(StandardCharsets.UTF_8));
            }
        });
        return response.writeWith(writeData);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
